package com.bear.cmcc.NetTestHTTP.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.util.Log;

import com.bear.cmcc.NetTestHTTP.component.HttpTestRoundInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestLogBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestRoundInfoBean;
import com.bear.cmcc.NetTestHTTP.component.ServersConfigBean;
import com.bear.cmcc.NetTestHTTP.constant.FtpConstant;
import com.bear.cmcc.NetTestHTTP.constant.HttpTestConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.db.NetTestDBControl;
import com.bear.cmcc.NetTestHTTP.util.HttpTestUtils;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.NetTestUtil;
import com.bear.cmcc.NetTestHTTP.util.TimeUtil;

/**
 * 测试线程
 * 
 * @author zhangheng
 * 
 */
public class HttpTestThread extends Thread {
	private String TAG = HttpTestThread.class.getSimpleName();

	double roundMaxSpeed, roundMinSpeed, oneTempSpeed, maxSpeed, minSpeed,
			roundAverageSpeed, roundFileSize;
	long roundTimes;// 每轮测试的开始时间
	int fileFQsize;// 下载时缓存分区大小
	String testDownFileName;// 下载文件的文件名
	NetTestLogBean netLogBean;
	HttpTestRoundInfoBean httpTestRoundInfoBean;
	int actualTestTimes, allTestTimes;// 实际测试的次数，当前是这一轮的第几次测试
	ServersConfigBean serverConfigBean;
	NetTestDBControl dbControl;
	private Context mContext;
	boolean timesFirstContrastSpeed;// 表示每次测试时是否是第一次对比速度，用来过滤掉第一次不保存maxspeed、minspeed

	public HttpTestThread(Context context) {
		this.mContext = context;
		// 初始化log信息
		initialLogParameter();
	}

	private void initializeRoundData() {
		if (httpTestRoundInfoBean == null) {
			httpTestRoundInfoBean = new HttpTestRoundInfoBean();
			httpTestRoundInfoBean.setStartTime(MyCommonUtil.getFormatDateTime());
//            firstSaveRound();
		}
	}
	
	   private void firstSaveRound() {
	        HttpTestRoundInfoBean bean = null;
	        if (httpTestRoundInfoBean != null) {
	        	httpTestRoundInfoBean.setEndTime(MyCommonUtil.getFormatDateTime());
	        	httpTestRoundInfoBean.setAverageSpeed(roundAverageSpeed);
	        	httpTestRoundInfoBean.setMaxSpeed(roundMaxSpeed);
	        	httpTestRoundInfoBean.setMinSpeed(roundMinSpeed);
	            httpTestRoundInfoBean.setTestTimes(actualTestTimes);
//	            httpTestRoundInfoBean.setDownServer(serverConfigBean.getServerName());
	            httpTestRoundInfoBean.setConsumeTime(TimeUtil.secondBetweenTime(
	            		httpTestRoundInfoBean.getStartTime(), httpTestRoundInfoBean.getEndTime()));
	        }
	        if (httpTestRoundInfoBean != null && (httpTestRoundInfoBean.getStartTime() != null)) {
	            HttpTestUtils.insertRoundInfo(httpTestRoundInfoBean, mContext);
	            bean = HttpTestUtils.getHttpTestRoundsInfosByStartTime(mContext,
	                    httpTestRoundInfoBean.getStartTime());
	            if (bean != null) {
	                httpTestRoundInfoBean.setPID(bean.getPID());
	            }
	        }
	        // 发送一轮测试开始的广播
	        HttpTestUtils.setOneRoundBeginBroad(mContext);
	    }

	/**
	 * 下载文件保存到本地
	 * 
	 * @param path
	 *            文件保存位置
	 * @param url
	 *            文件地址
	 * @throws IOException
	 */
	public boolean testDownload(String url, String path, long startTime)
			throws IOException {
		Log.d(TAG, "path:" + path);
		Log.d(TAG, "url:" + url);
		boolean success = false;

		int fileLength = 0;
		URL urlT = null;
		URLConnection connection = null;
		InputStream stream = null;
		long startTimeTemp = 0;
		long endTime = System.currentTimeMillis();

		try {
			urlT = new URL(url);
			connection = urlT.openConnection();
			connection.setConnectTimeout(100000);
			connection.setReadTimeout(100000);
			fileLength = connection.getContentLength();
			stream = connection.getInputStream();

			long onestartTime = System.currentTimeMillis();// 用来对比log
			long speedonestartTime = System.currentTimeMillis();// 用来对比速率
			long roundSpeedts = 0;
			int onesize = 0;
			int oneSpeedSize = 0;

			startTimeTemp = System.currentTimeMillis();
			if (stream != null) {
				byte[] b = new byte[fileFQsize];
				int j = 0;
				double temp = 0;
				maxSpeed = 0;
				minSpeed = 0;
				int allsum = 0;

				while ((j = stream.read(b, 0, fileFQsize)) != -1) {
					long oneendTime = System.currentTimeMillis();
					long speedoneendTime = System.currentTimeMillis();
					long ts = oneendTime - onestartTime;
					long speedts = speedoneendTime - speedonestartTime;
					roundSpeedts = roundTimes + (oneendTime - onestartTime);
					onesize += j;
					oneSpeedSize += j;
					roundFileSize += j;
					allsum = allsum + j;

					if (speedts >= 200)// 每200ms对比一次speed
					{
						// 获取轮平均速度
						temp = (double) ((double) roundFileSize / roundSpeedts
								/ 1024 * 1000 * MyCommonConstant.NetTestConstant.addMultiple);
						if (temp > 0) {
							roundAverageSpeed = temp;// 过滤零值
						}

						oneTempSpeed = (double) ((double) oneSpeedSize
								/ speedts / 1024 * 1000 * MyCommonConstant.NetTestConstant.addMultiple);

						if (!timesFirstContrastSpeed) {
							if (maxSpeed == 0)
								maxSpeed = oneTempSpeed;
							if (minSpeed == 0)
								minSpeed = oneTempSpeed;
							if (roundMaxSpeed == 0)
								roundMaxSpeed = oneTempSpeed;
							if (roundMinSpeed == 0)
								roundMinSpeed = oneTempSpeed;

							maxSpeed = (maxSpeed < oneTempSpeed) ? oneTempSpeed
									: maxSpeed;
							minSpeed = (minSpeed > oneTempSpeed) ? oneTempSpeed
									: minSpeed;
							roundMaxSpeed = (roundMaxSpeed < oneTempSpeed) ? oneTempSpeed
									: roundMaxSpeed;
							roundMinSpeed = (roundMinSpeed > oneTempSpeed) ? oneTempSpeed
									: roundMinSpeed;
						}
						timesFirstContrastSpeed = false;
						speedonestartTime = speedoneendTime;
						oneSpeedSize = 0;
						HttpTestUtils.sendHttpTestSpeedBroad(roundAverageSpeed,
								roundMaxSpeed, roundMinSpeed, mContext);

					}
				}

			}
			Log.i(TAG, "roundAverageSpeed=" + String.valueOf(roundAverageSpeed));
			success = true;
		} catch (Exception e) {
			Log.e("exception : ", e.getMessage() + "");

		} finally {
			try {
				if (stream != null) {
					stream.close();
				}
			} catch (Exception e) {
				Log.e("exception : ", e.getMessage());
			}

		}
		return success;
	}

	@Override
	public void run() {
		Log.i(TAG, "run--begin");
		boolean success = false;
		try {
			// 初始化轮数据
			initializeRoundData();

			if (MyCommonUtil.isNetworkAviable(mContext)) {
				String url = HttpTestConstant.TestUrl.sina;
				File fileDir = mContext.getFilesDir();
				String path = fileDir.getAbsolutePath() + "/"
						+ testDownFileName;

				long beginTime = System.currentTimeMillis();
				success = testDownload(url, path, beginTime);
				long endTime = System.currentTimeMillis();
				roundTimes = roundTimes + (endTime - beginTime);

				if (httpTestRoundInfoBean != null) {
					httpTestRoundInfoBean.setEndTime(MyCommonUtil
							.getFormatDateTime());
					httpTestRoundInfoBean.setAverageSpeed(roundAverageSpeed);
				}
				endRound();
				if (!success)
					sleep(FtpConstant.NET_TEST_FTP__DEFAULT_SLEEP);

			} else {
				sleep(FtpConstant.NET_TEST_FTP__DEFAULT_SLEEP);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
		}
		super.run();
	}

	/*
	 * 初始化netLogBean、fileFQsize、testDownFileName对象
	 */
	private void initialLogParameter() {
		netLogBean = new NetTestLogBean();
		netLogBean.setlogTime(MyCommonUtil.getCurDate());
		fileFQsize = NetTestUtil.getNetworkInfo(mContext, netLogBean);
		testDownFileName = MyCommonUtil.getDownFileName(MyCommonUtil
				.getNetWorkType(mContext));
	}

	/*
	 * 结束一轮测试保存信息
	 */
	public void endRound() {
		roundFileSize = 0;
		if (httpTestRoundInfoBean != null) {
			httpTestRoundInfoBean.setEndTime(MyCommonUtil.getFormatDateTime());
			httpTestRoundInfoBean.setAverageSpeed(roundAverageSpeed);
			httpTestRoundInfoBean.setMaxSpeed(roundMaxSpeed);
			httpTestRoundInfoBean.setMinSpeed(roundMinSpeed);
//			httpTestRoundInfoBean
//					.setDownServer(serverConfigBean.getServerName());
			httpTestRoundInfoBean.setConsumeTime(TimeUtil.secondBetweenTime(
					httpTestRoundInfoBean.getStartTime(),
					httpTestRoundInfoBean.getEndTime()));
		}
		if (httpTestRoundInfoBean != null
				&& httpTestRoundInfoBean.getTestTimes() >= 0) {
			HttpTestUtils.updateOrCreateTestRoundInfo(httpTestRoundInfoBean,
					mContext);
			httpTestRoundInfoBean = null;
		}
		// 发送一轮测试结束的广播
		HttpTestUtils.setOneRoundFinishBroad(mContext);		
		HttpTestUtils.stopHttpTestService(mContext, 0);
	}

	@Override
	public void interrupt() {
		// TODO Auto-generated method stub
		super.interrupt();
	}
}